//
//  ParseEventXML.m
//  cliqset
//
//  Created by David Hinson on 2/25/09.
//  Copyright 2009 Sumner Systems Management, Inc.. All rights reserved.
//

#import "ParseEventXMLReader.h"

@implementation ParseEventXMLReader

@synthesize mode                     = _mode;
@synthesize contentOfCurrentProperty = _contentOfCurrentProperty;
@synthesize currentEventObject       = _currentEventObject;
@synthesize currentResourceObject    = _currentResourceObject;

NSString *strEvent           = @"Event";
NSString *strCreateDate      = @"CreateDate";
NSString *strEventType       = @"EventType";
NSString *strTitle           = @"Title";
NSString *strBody            = @"Body";
NSString *strUrl             = @"Url";
NSString *strEventIdentifier = @"EventIdentifier";
NSString *strConsumerKey     = @"ConsumerKey";
NSString *strServiceName     = @"Name";
NSString *strResources       = @"Resources";
NSString *strResource        = @"Resource";
NSString *strResourceName    = @"Name";
NSString *strResourceValue   = @"Value";
NSString *strLogoURL         = @"LocoURL";
NSString *strIconURL         = @"IconURL";
NSString *strWebsiteURL      = @"WebsiteURL";
NSString *strUserIdentifier  = @"UserIdentifier";
NSString *strHonorificPrefix = @"HonorificPrefix";
NSString *strHonorificSuffix = @"HonorificSuffix";
NSString *strEventGivenName  = @"GivenName";
NSString *strEventMiddleName = @"MiddleName";
NSString *strEventFamilyName = @"FamilyName";
NSString *strGender          = @"Gender";
NSString *strAvatar          = @"Avatar";
NSString *strEventLocality   = @"Locality";
NSString *strEventRegion     = @"Region";
NSString *strEventCountry    = @"Country";
NSString *strEventPostCode   = @"PostCode";

-(id)init {
	[super init];
	
	return self;
}

-(void)resetVars {
	
	self.contentOfCurrentProperty = nil;

	if (@selector(_currentResourceObject) && _currentResourceObject!=nil && self.currentResourceObject) {
		[self.currentResourceObject release];
		self.currentResourceObject = nil;
	}

	if (@selector(_currentEventObject) && _currentEventObject!=nil && self.currentEventObject) {
		
		[self.currentEventObject.sourceService release];
		[self.currentEventObject.sourceUser release];
		
		[self.currentEventObject release];
		self.currentEventObject = nil;
	}	
}

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
	[self resetVars];
}

- (void)parseXMLFileAtData:(NSData *)data parseError:(NSError **)error
{	
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
	
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];
	
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    
    [parser parse];
    
    NSError *parseError = [parser parserError];
    if (parseError && error) {
        *error = parseError;
    }
	
	[self resetVars];
    
    [parser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) {
        elementName = qName;
    }
	
	if ([elementName isEqualToString:strEvent]) {		
		
		[self resetVars];
		
		self.currentEventObject               = [[Event alloc] init];
		self.currentEventObject.sourceService = [[SourceService alloc] init];
		self.currentEventObject.sourceUser    = [[BasicProfile alloc] init];
		
	} else if ([elementName isEqualToString:strEventIdentifier]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strCreateDate]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventType]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strTitle]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strBody]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strUrl]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strConsumerKey]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strServiceName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strResourceValue]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strLogoURL]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strIconURL]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strWebsiteURL]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strUserIdentifier]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strHonorificPrefix]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strHonorificSuffix]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventGivenName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventMiddleName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventFamilyName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strGender]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strAvatar]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventLocality]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventRegion]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventCountry]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEventPostCode]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strResources]) {
		//self.currentEventObject.resources = [[NSMutableArray alloc] init];
	} else if ([elementName isEqualToString:strResource]) {
		self.currentResourceObject    = [[Resource alloc] init];
        self.contentOfCurrentProperty = [NSMutableString string];
    } else {
        // The element isn't one that we care about, so set the property that holds the 
        // character content of the current element to nil. That way, in the parser:foundCharacters:
        // callback, the string that the parser reports will be ignored.
        self.contentOfCurrentProperty = nil;
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
	NSMutableData *imageData;
	NSString *imageURL;
	NSURL *url;
	NSMutableURLRequest* request;
	NSURLResponse* response;
	NSError* error;
	
    if (qName) {
        elementName = qName;
    }
	
	// Resource
    if ([elementName isEqualToString:strResource]) {
		if (self.contentOfCurrentProperty) {
			[self.currentEventObject.resources addObject:self.currentResourceObject];
			[self.currentResourceObject release];
			self.currentResourceObject = nil;
			//self.currentEventObject.eventIdentifier = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.eventIdentifier = (NSMutableString*)@"";
		}
	}
	
	// Event Identifier
    if ([elementName isEqualToString:strEventIdentifier]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.eventIdentifier = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.eventIdentifier = (NSMutableString*)@"";
		}
	}

	// Create Date
    if ([elementName isEqualToString:strCreateDate]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.createDate = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.eventType = (NSMutableString*)@"";
		}
	}
	
	// Event Type
    if ([elementName isEqualToString:strEventType]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.eventType = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.eventType = (NSMutableString*)@"";
		}
	}
	
	// Title
    if ([elementName isEqualToString:strTitle]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.title = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.title = (NSMutableString*)@"";
		}
	}
	
	// Body
    if ([elementName isEqualToString:strBody]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.body = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.body = (NSMutableString*)@"";
		}
	}
	
	// Url
    if ([elementName isEqualToString:strUrl]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.url = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.url = (NSMutableString*)@"";
		}
	}
	
	// Consumer Key
    if ([elementName isEqualToString:strConsumerKey]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceService.consumerKey = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceService.consumerKey = (NSMutableString*)@"";
		}
	}	
	
	// Name
    if ([elementName isEqualToString:strServiceName] && !self.currentResourceObject) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceService.name = self.contentOfCurrentProperty;
			} 
		else {
			self.currentEventObject.sourceService.name = (NSMutableString*)@"";
			}
	}	
	
	// This is a resource name
    if ([elementName isEqualToString:strResourceName] && self.currentResourceObject) {
		if (self.contentOfCurrentProperty) {
			self.currentResourceObject.name = self.contentOfCurrentProperty;
			}
		else { 
			self.currentResourceObject.name = (NSMutableString*)@"";
		}
	}
	
	// Resource Value
    if ([elementName isEqualToString:strResourceValue]) {
		if (self.contentOfCurrentProperty) {
			self.currentResourceObject.value = self.contentOfCurrentProperty;
		} else {
			self.currentResourceObject.value = (NSMutableString*)@"";
		}
	}	
	
	// Logo URL
    if ([elementName isEqualToString:strLogoURL]) {
		// This is a service name
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceService.logoURL = self.contentOfCurrentProperty;
			imageURL        = self.contentOfCurrentProperty;
			
			NSLog(@"%@", imageURL);
			
			url             = [NSURL URLWithString:imageURL];
			request         = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
			
			imageData       = (NSMutableData*)[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
			self.currentEventObject.sourceService.logoBlob = (NSMutableData*)imageData;
		} else {
			self.currentEventObject.sourceService.logoURL = (NSMutableString*)@"";
			}
	}	
	
	// Icon URL
    if ([elementName isEqualToString:strIconURL]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceService.iconURL = self.contentOfCurrentProperty;
			imageURL        = self.contentOfCurrentProperty;
			
			// NSLog(@"Icon URL: %@", imageURL);
			
			url             = [NSURL URLWithString:imageURL];
			request         = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
			
			imageData       = (NSMutableData*)[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
			self.currentEventObject.sourceService.iconBlob = (NSMutableData*)imageData;
		} else {
			self.currentEventObject.sourceService.iconURL  = (NSMutableString*)@"";
			self.currentEventObject.sourceService.iconBlob = nil;
		}
	}	
	
	// Website URL
    if ([elementName isEqualToString:strWebsiteURL]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceService.websiteURL = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceService.websiteURL = (NSMutableString*)@"";
		}
	}	
	
	// User Identifier
    if ([elementName isEqualToString:strUserIdentifier]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.userIdentifier = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.userIdentifier = (NSMutableString*)@"";
		}
	}	
	
	// Honorific Prefix
    if ([elementName isEqualToString:strHonorificPrefix]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.honorificPrefix = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.honorificPrefix = (NSMutableString*)@"";
		}
	}	
	
	// Honorific Suffic
    if ([elementName isEqualToString:strHonorificSuffix]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.honorificSuffix = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.honorificSuffix = (NSMutableString*)@"";
		}
	}	
	
	// Given Name
    if ([elementName isEqualToString:strEventGivenName]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.givenName = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.givenName = (NSMutableString*)@"";
		}
	}	
	
	// Middle Name
    if ([elementName isEqualToString:strEventMiddleName]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.middleName = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.middleName = (NSMutableString*)@"";
		}
	}	
	
	// Family Name
    if ([elementName isEqualToString:strEventFamilyName]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.familyName = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.familyName = (NSMutableString*)@"";
		}
	}	
	
	// Gender
    if ([elementName isEqualToString:strGender]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.gender = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.gender = (NSMutableString*)@"";
		}
	}	
	
	// Avatar
    if ([elementName isEqualToString:strAvatar]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.avatarURL  = self.contentOfCurrentProperty;
			imageURL        = self.contentOfCurrentProperty;
			
			// NSLog(@"Avatar URL: %@", imageURL);
			
			url             = [NSURL URLWithString:imageURL];
			request         = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
			
			imageData       = (NSMutableData*)[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
			self.currentEventObject.sourceUser.avatarBlob = (NSMutableData*)imageData;
		} else {
			self.currentEventObject.sourceUser.avatarURL  = (NSMutableString*)@"";
			self.currentEventObject.sourceUser.avatarBlob = nil;
		}
	}	
	
	// Hometown Locality
    if ([elementName isEqualToString:strEventLocality]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.locality = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.locality = (NSMutableString*)@"";
		}
	}	
	
	// Hometown Region
    if ([elementName isEqualToString:strEventRegion]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.region = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.region = (NSMutableString*)@"";
		}
	}	
	
	// Hometown Country
    if ([elementName isEqualToString:strEventCountry]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.country = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.country = (NSMutableString*)@"";
		}
	}	
	
	// Hometown Post Code
    if ([elementName isEqualToString:strEventPostCode]) {
		if (self.contentOfCurrentProperty) {
			self.currentEventObject.sourceUser.postCode = self.contentOfCurrentProperty;
		} else {
			self.currentEventObject.sourceUser.postCode = (NSMutableString*)@"";
		}
	}	
	
	if ([elementName isEqualToString:strEvent]) {
		// we will write the Event to an array here...
		if (self.currentEventObject) {
			self.currentEventObject.mode = self.mode;
			[(id)[[UIApplication sharedApplication] delegate] performSelectorOnMainThread:@selector(addEvent:) withObject:self.currentEventObject waitUntilDone:YES];
		}
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.contentOfCurrentProperty) {
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
		if (string) {
			string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
			string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
			string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
			[self.contentOfCurrentProperty appendString:string];
		}
    }
}

-(void) dealloc {
	[_contentOfCurrentProperty release];
	[_currentResourceObject release];	
	[_currentEventObject release];	
	[super dealloc];
}

@end
